import pandas as pd
import subprocess
import sys
import os

def run():
    #执行gen_params.py
    # command = "python3 ./gen_params.py {}".format(times)
    # result = subprocess.run(command, shell=True, capture_output=True, text=True)

    data = pd.read_csv('./input_params/MNKC_data.csv')

    operator_path = os.getcwd()

    # 最后要写入的结果表格的表头
    # results = pd.DataFrame(columns=["problemCount", "mList", "nList", "kList", "time_us", "Tflops", "utilization_ratio"])
    results = pd.DataFrame(columns=["zeroPaddingM", "zeroPaddingN", "zeroPaddingK", "batchCount", "time_us", "Tflops"])

    prof_data_path = "./output_result/batch_prof_data.csv"

    # 获取每行数据（不包含表头，只是在第0行写入的时候加上表头）
    for index, row in data.iterrows(): 
        
        col1 = row.iloc[0]
        col2 = row.iloc[1]
        col3 = row.iloc[2]
        col4 = row.iloc[3]

        command = "./run_profiling.sh {} {} {} {}".format(col1, col2, col3, col4)
        result = subprocess.run(command, shell=True, capture_output=True, text=True)

        # prof.py最后一行输出需要的数据
        last_line1 = result.stdout.strip().splitlines()[-1]
        # 对最后一行切分得到数据（默认按照空格切分）
        parts = last_line1.split()  

        zeroPaddingM = parts[1] 
        zeroPaddingN = parts[3]          
        zeroPaddingK = parts[5]               
        batchCount = parts[7]             
        time_us = parts[9]  
        Tflops = parts[11]

        print(format(last_line1))
        frame =  pd.DataFrame([[zeroPaddingM, zeroPaddingN, zeroPaddingK, batchCount, time_us, Tflops]], 
                            columns=["zeroPaddingM", "zeroPaddingN", "zeroPaddingK", "batchCount", "time_us", "Tflops"])

        if index == 0:

            frame.to_csv(prof_data_path, mode='w', header=True, index=False)

        else:
            frame.to_csv(prof_data_path, mode='a', header=not os.path.exists(prof_data_path), index=False)

            
            

if __name__ == "__main__":
    # times = int(sys.argv[1])  # 批量次数
    run()